//
//  giftInfoImageDataBase.m
//  tcpoctest
//
//  Created by gump on 5/29/13.
//  Copyright (c) 2013 gump. All rights reserved.
//

#import "giftInfoImageDataBase.h"
#import "GiftInfoDataSource.h"

@implementation giftInfoImageDataBase

-(void)creatTable
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:@"create table if not exists giftinfoimage(giftid text,\
localpath text)"];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)initData
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM giftinfoimage"];
    FMResultSet *s = [db executeQuery:strsql];
    
    [[DataControl shareControl].giftInfoDS delAllImageDic];
    
    while ([s next]) {
        [[DataControl shareControl].giftInfoDS AddPathToImageDic:[s stringForColumn:@"localpath"]
                                                          withID:[s stringForColumn:@"giftid"]];
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)insertPath:(NSString *)strpath withID:(NSString *)strid
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM giftinfoimage WHERE giftid = '%@'",
                        strid];
    
    
    FMResultSet *s = [db executeQuery:strsql];
    if([s next])
    {
        strsql = [NSString stringWithFormat:@"update giftinfoimage \
set localpath = '%@' WHERE giftid = '%@'"
                  ,strpath
                  ,strid];
    }
    else
    {
        strsql = [NSString stringWithFormat:@"insert into giftinfoimage \
(localpath,giftid) \
values('%@','%@')"
                  ,strpath
                  ,strid];
    }
    
    [db executeUpdate:strsql];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

@end
